package com.service;

import com.alibaba.dingtalk.openapi.Env;
import com.alibaba.dingtalk.openapi.auth.AuthHelper;
import com.alibaba.dingtalk.openapi.message.LightAppMessageDelivery;
import com.alibaba.dingtalk.openapi.message.MessageHelper;
import com.alibaba.fastjson.JSONObject;
import com.dao.IPurchaseDao;
import com.dao.LogDao;
import com.dingtalk.open.client.api.model.corp.MessageBody;
import com.dingtalk.open.client.api.model.corp.MessageType;
import com.nc.purchase.PurchaseWebService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;


@Component
public class PurchaseService {

    @Autowired
    private PurchaseWebService purchaseWebService;
    @Autowired
    private IPurchaseDao purchaseDao;
    @Autowired
    private LogDao logDao;

    /**
     * 根据组织id（orgId）获取需求部门列表
     *
     * @param orgId
     * @return
     */
    public Map<String, Object> getDeptListByOrgId(String orgId) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<Object> list = purchaseDao.getDeptListByOrgId(orgId);
            map.put("data", list);
            map.put("code", 100);
        } catch (Exception e) {
            map.put("code", 101);
            map.put("errMsg", e.getMessage());
        }
        return map;
    }

    /**
     * 根据组织Id（orgId） 获取采购组织列表
     *
     * @param orgId
     * @return
     */
    public Map<String, Object> getPurchaseOrgListByOrgId(String orgId) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<Object> list = purchaseDao.getPurchaseOrgListByOrgId(orgId);
            map.put("data", list);
            map.put("code", 100);
        } catch (Exception e) {
            map.put("code", 101);
            map.put("errMsg", e.getMessage());
        }
        return map;
    }


    /**
     * 库存组织列表
     *
     * @param orgId
     * @return
     */
    public Map<String, Object> getStockOrgListByOrgId(String orgId) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<Object> list = purchaseDao.getStockOrgListByOrgId(orgId);
            map.put("code", 100);
            map.put("data", list);
        } catch (Exception e) {
            map.put("code", 101);
            map.put("errMsg", e.getMessage());
        }
        return map;
    }

    /**
     * 获取请购类型列表
     *
     * @return
     */
    public Map<String, Object> getBillTypeList() {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<Object> list = purchaseDao.getBillTypeList();
            map.put("code", 100);
            map.put("data", list);
        } catch (Exception e) {
            map.put("code", 101);
            map.put("errMsg", e.getMessage());
        }
        return map;
    }

    /**
     * 提交物料需求信息
     * 保存在mysql 表中
     *
     * @param userId
     * @param userName
     * @param jobNumber
     * @param pk_stockorg
     * @param ctrantypeid
     * @param vmemo
     * @param detailList  UUID.randomUUID().toString().replace("-", "") 随机数流水号
     * @return
     */
    // TODO: 2018/1/8 临时备注
    public Map<String, Object> subPurchaseByObj(String userId, String userName, String jobNumber, String pk_stockorg, String ctrantypeid, String vmemo, List<Map<String, String>> detailList) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String ordernumber = UUID.randomUUID().toString().replace("-", "");
            purchaseDao.subPurchaseByObj(userId, userName, jobNumber, pk_stockorg, ctrantypeid, vmemo, ordernumber);
            insertPurchase_detail(detailList, ordernumber);
            map.put("code", 100);
            logDao.logInfo("提交物料需求信息", userName, userId);
        } catch (Exception e) {
            map.put("code", 101);
            map.put("errMsg", e.getMessage());
        }
        return map;
    }

    private void insertPurchase_detail(List<Map<String, String>> detailList, String ordernumber) throws Exception {
        try {
            for (Map<String, String> item : detailList) {
                String pk_purchaseorg = item.get("pk_purchaseorg");
                String pk_material = item.get("pk_material");
                String castunitid = item.get("castunitid");
                String nastnum = item.get("nastnum");
                String dreqdate = item.get("dreqdate");
                String pk_reqdept = item.get("pk_reqdept");
//                String vbmemo = item.get("vbmemo");
                purchaseDao.insertPurchaseDetail(pk_purchaseorg, pk_material, castunitid, nastnum, dreqdate, pk_reqdept, ordernumber);
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /***************************************************************************************************************************************************************/
    /****************************************************************************PC端查看***************************************************************************/
    /***************************************************************************************************************************************************************/

    /**
     * PC端管理员查询移动端提交的请购
     *
     * @param start
     * @param limit
     * @return
     */
    public Map<String, Object> getPcPurchaseList(Integer start, Integer limit, Integer status, String userName) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<Object> findList = purchaseDao.getPcPurchaseList(start, limit, status, userName);
            Integer findCount = purchaseDao.queryPcPurchaseCount(status, userName);
            List<Object> resultList = findPurchaseDetailList(findList);
            map.put("code", 100);
            map.put("data", resultList);
            map.put("count",findCount);
        } catch (Exception e) {
            map.put("code", 101);
            map.put("errMsg", e.getMessage());
        }
        return map;
    }

    private List<Object> findPurchaseDetailList(List<Object> list) throws Exception {
        List<Object> resultList = new ArrayList<Object>();
        try {
            for (Object obj : list) {
                Map<String, String> objMap = (Map<String, String>) obj;
                String ordernumber = objMap.get("ordernumber");
                Map<String, Object> map = new HashMap<String, Object>();
                List<Object> detailList = purchaseDao.findDetailByOrderNum(ordernumber);
                map.put("info", objMap);
                map.put("detail", detailList);
                resultList.add(map);
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
        return resultList;
    }

    /**
     * PC端审核操作
     */
    public Map<String, Object> examinePurchase(String ordernumber, Integer status, String message, String jobNumber) {

        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<Object> findList = purchaseDao.getFrPurchaseZeroByOrderNum(ordernumber);
            if (findList.size() == 0) {
                map.put("code", 101);
                map.put("errMsg", "找不到对应的表结构");
                return map;
            }
            Map<String, Object> purchaseMap = (Map<String, Object>) findList.get(0);
            String userId = (String) purchaseMap.get("userId");
            if (status == 1) {//审核通过
                Map<String, Object> insertMap = new HashMap<String, Object>();
                List<Object> detailList = purchaseDao.getPurchaseDetailByOrderNumber(ordernumber);
                purchaseMap.put("detail", detailList);

                List headinfoList = new ArrayList();
                headinfoList.add(purchaseMap);
                Map<String, Object> endMap = new HashMap<String, Object>();
                endMap.put("headinfo", headinfoList);

                //调用ws
                JSONObject resultObj = purchaseWebService.startPruchase(endMap);
                Integer resultNum = (Integer) resultObj.get("result");
                String resultMsg = (String) resultObj.get("message");
                if (resultNum == 1) {
                    sendMessage(userId, "您的物料审批已通过");
                    purchaseDao.adoptPurchaseSetDate(status, jobNumber, ordernumber);
                    logDao.logInfo("PC端审核操作--通过", null, null);
                } else {
                    map.put("code", 101);
                    map.put("errMsg", resultMsg);
                }
            }
            if (status == 2) {//拒绝
                sendMessage(userId, message);
                purchaseDao.refuseFrPurchaseByOrderNumber(ordernumber, status, message);
                logDao.logInfo("PC端审核操作--拒绝", null, null);
            }
        } catch (Exception e) {
            map.put("code", 101);
            map.put("errMsg", e.getMessage());
            return map;
        }
        System.out.println("走你！！");
        map.put("code", 100);
        return map;
    }

    /**
     * 钉钉消息推送接口
     */
    private void sendMessage(String userId, String msg) throws Exception {

        // 获取access token
        String accessToken = AuthHelper.getAccessToken();
        // 发送微应用消息
        String toUsers = userId;
        String toParties = null;
        String agentId = Env.AGENT_ID + "";
        LightAppMessageDelivery lightAppMessageDelivery = new LightAppMessageDelivery(toUsers, toParties, agentId);

        MessageBody.TextBody textBody = new MessageBody.TextBody();
        textBody.setContent(msg);

        lightAppMessageDelivery.withMessage(MessageType.TEXT, textBody);
        MessageHelper.send(accessToken, lightAppMessageDelivery);
        System.out.println("成功发送 微应用文本消息");
    }

    /**
     * PC端 根据ordernumber 修改移动端提交的请购信息详情
     *
     * @param userId
     * @param userName
     * @param jobNumber
     * @param pk_stockorg
     * @param ctrantypeid
     * @param vmemo
     * @param detailList
     * @return
     */
    public Map<String, Object> editPurchaseByObj(String ordernumber, String userId, String userName, String jobNumber, String pk_stockorg, String ctrantypeid, String vmemo, List<Map<String, String>> detailList) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<Object> queryList = purchaseDao.queryPurchaseById(ordernumber);
            if (queryList.size() == 0) {
                map.put("code", 101);
                map.put("errMsg", "fr_purchase为空");
                return map;
            }
            purchaseDao.editPurchaseByOrderNumber(userId, userName, jobNumber, pk_stockorg, ctrantypeid, vmemo, ordernumber);
            updatePurchase_detail(detailList, ordernumber);
            map.put("code", 100);
            logDao.logInfo("PC端管理员修改物料需求信息", userName, userId);
        } catch (Exception e) {
            map.put("code", 101);
            map.put("errMsg", e.getMessage());
        }
        return map;
    }

    private void updatePurchase_detail(List<Map<String, String>> detailList, String ordernumber) throws Exception {
        try {
            for (Map<String, String> item : detailList) {
                String pk_purchaseorg = item.get("pk_purchaseorg");
                String pk_material = item.get("pk_material");
                String castunitid = item.get("castunitid");
                String nastnum = item.get("nastnum");
                String dreqdate = item.get("dreqdate");
                String pk_reqdept = item.get("pk_reqdept");
//                String vbmemo = item.get("vbmemo");
                purchaseDao.updatePurchase_detailByOrderNumber(pk_purchaseorg, pk_material, castunitid, nastnum, dreqdate, pk_reqdept, ordernumber);
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
    }
}
